<template>
  <div class="container my-4">
    <div class="card shadow-sm rounded-3">
      <!-- Header -->
      <div class="card-header d-flex justify-content-between align-items-center">
        <h6 class="mb-0 fw-bold">任务列表</h6>
        <button class="btn btn-sm btn-primary rounded-pill" @click="openAdd">
          <i class="bi bi-plus-circle"></i> 添加任务
        </button>
      </div>

      <!-- Table -->
      <div class="card-body p-0">
        <table class="table table-hover align-middle mb-0">
          <thead class="table-light">
            <tr class="text-center align-middle">
              <th>ID</th>
              <th>任务名</th>
              <th>运行状态</th>
              <th>运行次数</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="task in tasks" :key="task.id">
              <td class="text-center align-middle">{{ task.id }}</td>
              <td class="text-center align-middle">{{ task.name }}</td>
              <td class="text-center align-middle">
                <span class="badge bg-secondary" v-if="task.status==='stopped'">未运行</span>
                <span class="badge bg-success" v-else-if="task.status==='running'">运行中</span>
                <span class="badge bg-primary" v-else-if="task.status==='success'">运行完成</span>
                <span class="badge bg-danger" v-else-if="task.status==='error'">执行失败</span>
                <span class="badge bg-info" v-else>{{ task.status }}</span>
              </td>
              <td class="text-center align-middle">{{ task.count }}</td>
              <td class="text-center align-middle">
                <button class="btn btn-sm btn-success me-1 rounded-pill"
                        @click="runTask(task)"
                        :disabled="loadingTasks[task.id]">
                  <template v-if="loadingTasks[task.id]">
                    <span class="spinner-border spinner-border-sm me-1"></span>运行中
                  </template>
                  <template v-else>
                    <i class="bi bi-play-fill"></i> 运行
                  </template>
                </button>

                <button class="btn btn-sm btn-warning me-1 rounded-pill" @click="openEdit(task)">
                  <i class="bi bi-pencil-fill"></i> 编辑
                </button>

                <button class="btn btn-sm btn-danger rounded-pill" @click="removeTaskConfirm(task)">
                  <i class="bi bi-trash-fill"></i> 删除
                </button>
              </td>
            </tr>

            <tr v-if="tasks.length===0">
              <td colspan="5" class="text-center py-3">暂无任务</td>
            </tr>
          </tbody>
        </table>
      </div>

      <!-- Add/Edit Modal -->
      <div class="modal fade" ref="taskModalRef" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg">
          <div class="modal-content rounded-4 shadow">
            <div class="modal-header">
              <h5 class="modal-title">{{ editingTask ? '编辑任务' : '添加任务' }}</h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
              <div class="mb-3">
                <label class="form-label">任务名</label>
                <input v-model="form.name" type="text" class="form-control" placeholder="请输入任务名" />
              </div>
              <div class="mb-3">
                <label class="form-label">YAML 模板</label>
                <textarea v-model="form.yaml" class="form-control" rows="12"></textarea>
              </div>
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary rounded-pill" data-bs-dismiss="modal">取消</button>
              <button type="button" class="btn btn-primary rounded-pill" @click="saveTask">
                {{ editingTask ? '保存修改' : '添加' }}
              </button>
            </div>
          </div>
        </div>
      </div>

      <!-- Delete Modal -->
      <div class="modal fade" ref="deleteModalRef" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered">
          <div class="modal-content rounded-4 shadow">
            <div class="modal-header">
              <h5 class="modal-title text-danger">
                <i class="bi bi-exclamation-triangle-fill me-2"></i>确认删除
              </h5>
              <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
              确认要删除任务 <b>{{ deletingTask?.name }}</b> 吗？此操作不可撤销。
            </div>
            <div class="modal-footer">
              <button type="button" class="btn btn-secondary rounded-pill" data-bs-dismiss="modal">取消</button>
              <button type="button" class="btn btn-danger rounded-pill" @click="confirmDelete">确认删除</button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <Toast />
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { Modal } from 'bootstrap'
import { useTaskStore } from '@/store/task'
import { storeToRefs } from 'pinia'
import { useToastStore } from '@/store/toast'
import Toast from './Toast.vue'

const taskStore = useTaskStore()
const { tasks } = storeToRefs(taskStore)
const toastStore = useToastStore()

// 控制按钮状态
const loadingTasks = reactive({})

// Delete modal
const deleteModalRef = ref(null)
let deleteModalInstance = null
const deletingTask = ref(null)

// Add/Edit modal
const taskModalRef = ref(null)
let taskModalInstance = null
const editingTask = ref(null)
const form = ref({ name: '', yaml: '' })

function getDefaultForm() {
  return {
    name: '',
    yaml: `# YAML 示例
name: demo
build:
  - echo build1
  - echo build2
deploy:
  platform: linux
  run:
    - echo run1
    - echo run2`
  }
}

// WebSocket
let ws = null
function connectWS() {
  const token = localStorage.getItem('token')
  if (!token) return

  const wsAddr = import.meta.env.VITE_WS_ADDR
  ws = new WebSocket(`ws://${wsAddr}/ws/task`, [token])

  ws.onopen = () => console.log('WebSocket 已连接')
  ws.onmessage = (event) => {
    try {
      const data = JSON.parse(event.data)
      const idx = tasks.value.findIndex(t => t.id === data.id)
      if (idx !== -1) {
        tasks.value[idx] = { ...tasks.value[idx], ...data } // 保证响应式
      }
    } catch (err) {
      console.error('WebSocket 消息解析错误', err)
    }
  }
  ws.onclose = () => setTimeout(connectWS, 3000)
  ws.onerror = (err) => { console.error('WebSocket 错误', err); ws.close() }
}

// 新增任务
function openAdd() {
  editingTask.value = null
  form.value = getDefaultForm()
  if (!taskModalInstance && taskModalRef.value) {
    taskModalInstance = new Modal(taskModalRef.value)
  }
  taskModalInstance?.show()
}

// 编辑任务
function openEdit(task) {
  editingTask.value = task
  form.value = { name: task.name, yaml: task.yaml || '' }
  if (!taskModalInstance && taskModalRef.value) {
    taskModalInstance = new Modal(taskModalRef.value)
  }
  taskModalInstance?.show()
}

// 保存任务
async function saveTask() {
  if (!form.value.name.trim()) return
  try {
    if (editingTask.value) {
      await taskStore.modifyTask(editingTask.value.id, { name: form.value.name, yaml: form.value.yaml })
      toastStore.showToast(`任务 "${form.value.name}" 已修改`, 'success')
    } else {
      await taskStore.createTask({ name: form.value.name, yaml: form.value.yaml })
      toastStore.showToast(`任务 "${form.value.name}" 已添加`, 'success')
    }
    taskModalInstance?.hide()
  } catch (err) {
    console.error(err)
    toastStore.showToast(`操作失败`, 'danger')
  }
}

// 删除任务
function removeTaskConfirm(task) {
  deletingTask.value = task
  if (!deleteModalInstance && deleteModalRef.value) {
    deleteModalInstance = new Modal(deleteModalRef.value)
  }
  deleteModalInstance?.show()
}

async function confirmDelete() {
  if (!deletingTask.value) return
  const taskToDelete = deletingTask.value
  deleteModalInstance?.hide()
  deletingTask.value = null
  try {
    await taskStore.removeTask(taskToDelete.id)
    toastStore.showToast(`任务 "${taskToDelete.name}" 已删除`, 'warning')
  } catch (err) {
    console.error(err)
    toastStore.showToast(`删除任务 "${taskToDelete.name}" 失败`, 'danger')
  }
}

// 运行任务
async function runTask(task) {
  const id = task.id
  if (loadingTasks[id]) return
  loadingTasks[id] = true
  toastStore.showToast(`任务 "${task.name}" 开始运行...`, 'info')

  try {
    await taskStore.runTaskNow(task)
    // 状态由 WebSocket 更新
  } catch (err) {
    console.error(err)
    toastStore.showToast(`任务 "${task.name}" 运行失败`, 'danger')
  } finally {
    loadingTasks[id] = false
  }
}

// 初始化
onMounted(async () => {
  await taskStore.getAllTasks()
  await nextTick()
  if (deleteModalRef.value) {
    deleteModalInstance = new Modal(deleteModalRef.value)
  }
  if (taskModalRef.value) {
    taskModalInstance = new Modal(taskModalRef.value)
  }
  connectWS()
})

onBeforeUnmount(() => {
  if (ws) ws.close()
})
</script>
